<?php namespace Connection;
use Workerman\Connection\ConnectionInterface;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\UdpConnection;
use Workerman\Events\EventInterface;

class TcpListenConnection extends ConnectionInterface {
    
    public function __construct($remote_address){  
        $socket = \stream_socket_server('tcp://'.$remote_address, $errno, $errstr) or exit; 
        Worker::$globalEvent->add($socket, EventInterface::EV_READ,[$this,'accept']); 
        $this->_remoteAddress = $remote_address; 
    }
    
    public function accept($socket){
        $client = stream_socket_accept($socket,$addr);
        call_user_func($this->onMessage,$client,$addr); 
    }
  
    public function send($send_buffer){
        throw new Exception("Error Processing Request", 1); 
    }
    

    /**
     * Close connection.
     *
     * @param mixed $data
     * @param bool  $raw
     * @return bool
     */
    public function close($data = null, $raw = false)
    {
        throw new Exception("Error Processing Request", 1); 
    }


    /**
     * Get remote IP.
     *
     * @return string
     */
    public function getRemoteIp()
    {
        $pos = strrpos($this->_remoteAddress, ':');
        if ($pos) {
            return trim(substr($this->_remoteAddress, 0, $pos), '[]');
        }
        return '';
    }

    /**
     * Get remote port.
     *
     * @return int
     */
    public function getRemotePort()
    {
        if ($this->_remoteAddress) {
            return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
        }
        return 0;
    }

}